<template>
  <div>
    <el-dialog v-if="enable" :visible.sync="enable" :title="`查询 数据库：${dbname}`" width="80%" :close-on-click-modal="false">
      <div class="dialog-db-query-text-editor">
        <codemirror v-model="query" :options="queryEditorOptions"></codemirror>
      </div>
      <div class="text-right mt-1">
        <el-select v-model="queryName" placeholder="请选择" size="mini" style="margin-right:10px;" clearable @change="actionQuerySnippetChanged">
          <el-option
            v-for="(snippet,name) in querySnippets"
            :key="name"
            :label="name"
            :value="name"
          ></el-option>
        </el-select>
        <el-button size="mini" :disabled="isSnippetDeleteAvailable" @click="actionQuerySnippetsDelete"><i class="el-icon-delete"></i></el-button>
        <el-button size="mini" @click="actionQuerySave"><i class="el-icon-download"></i></el-button>
        <el-button size="mini" @click="actionExecuteQuery"><i class="el-icon-refresh"></i></el-button>
      </div>

      <div class="block-result">
        <table v-if="result.length > 0" class="table-result">
          <thead>
            <tr>
              <th v-for="key in Object.keys(result[0])" :key="key">{{key}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in result" :key="index">
              <td v-for="(item, cIndex) in row" :key="cIndex">{{item}}</td>
            </tr>
          </tbody>
        </table>
      </div>
    
    </el-dialog>
  </div>
</template>
<script>
import fsPromises from 'fs/promises';
import { codemirror } from 'vue-codemirror'
import "codemirror/theme/ambiance.css";
import Common from '../../utils/Common.js';
require("codemirror/mode/sql/sql.js");
export default {
    components : {
        codemirror,
    },
    data() {
        return {
            dbname : null,
            connection : null,
            enable : false,
            querySnippets : {},
            query : null,
            queryName : null,
            result : [],
            queryEditorOptions : {
                mode:'sql',
                theme: 'ambiance',
                readOnly:false,
                lineNumbers:false,
                lineWrapping:true,
                autofocus:true,
            },
        };
    },
    computed : {
        // 是否可以删除当前片段
        isSnippetDeleteAvailable() {
            return Common.isVarEmpty(this.queryName);
        },
    },
    methods : {
        // 打开弹框
        async open(connection, name) {
            this.dbname = name;
            this.connection = connection;
            this.query = '';
            this.result = [];

            let server = this.$store.getters.serverCurrent;
            let queryFolder = server.getPath('database-query');
            try {
                await fsPromises.access(queryFolder, fsPromises.F_OK);
                let files = await fsPromises.readdir(queryFolder);
                for ( let i=0; i<files.length; i++ ) {
                    let snippetPath = server.getPath(`database-query/${files[i]}`);
                    let snippet = await fsPromises.readFile(snippetPath, {encoding:'utf8'});
                    snippet = JSON.parse(snippet);
                    let name = files[i].substring(0, files[i].length-5);
                    this.querySnippets[name] = snippet;
                }
            } catch (e) {}

            await this.connection.execute(`use ${name}`);
            this.enable = true;
        },

        // 执行查询
        async actionExecuteQuery() {
            let result = null;
            try {
                result = await this.connection.execute(this.query);
            } catch ( error ) {
                this.$message.error(error.message);
                return;
            }

            this.result = result;
        },

        // 保存查询
        async actionQuerySave() {
            if ( Common.isVarEmpty(this.queryName) ) {
                let queryName = null;
                try {
                    queryName = await this.$prompt('请输入查询脚本名称', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    });
                } catch {
                    return;
                }
                this.queryName = queryName.value;
            }

            let server = this.$store.getters.serverCurrent;
            let queryFolder = server.getPath('database-query');
            try {
                await fsPromises.access(queryFolder, fsPromises.F_OK);
            } catch (e) {
                await fsPromises.mkdir(queryFolder);
            }

            let queryPath = server.getPath(`database-query/${this.queryName}.json`);
            let snippet = {
                query : this.query,
                dbname : this.dbname,
            }
            let content = JSON.stringify(snippet, null, 2);
            await fsPromises.writeFile(queryPath, content);
            this.querySnippets[this.queryName] = snippet;
            this.$forceUpdate();
        },

        /**
         * 切换当前片段
         */
        actionQuerySnippetChanged() {
            if ( Common.isVarEmpty(this.queryName) ) {
                return ;
            }
            this.query = this.querySnippets[this.queryName].query;
        },

        // 删除查询片段
        async actionQuerySnippetsDelete() {
            if ( Common.isVarEmpty(this.queryName) ) {
                return ;
            }
            try {
                await this.$confirm('此操作将永久删除该查询片段, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let server = this.$store.getters.serverCurrent;
            let queryPath = server.getPath(`database-query/${this.queryName}.json`);
            await fsPromises.unlink(queryPath);
            delete this.querySnippets[this.queryName];
            this.queryName = null;
            this.$forceUpdate();
        },
    },
}
</script>
<style>
.dialog-db-query-text-editor .CodeMirror {height: 100px !important;}
</style>
<style scoped>
.block-result {width: 100%;overflow: auto;margin-top: 10px;max-height: 500px;border-top: solid 1px #efefef;border-bottom: solid 1px #efefef;}
.block-result::-webkit-scrollbar { width: 10px; height: 10px; }
.block-result::-webkit-scrollbar-thumb {border-radius: 10px;box-shadow: inset 0 0 5px rgba(0,0,0,0.2); background: #535353;}
.block-result::-webkit-scrollbar-track {box-shadow: inset 0 0 5px rgba(0,0,0,0.2);border-radius: 10px;background: #EDEDED;}
.table-result td, .table-result th { white-space: nowrap; }
.table-result, .table-result tr th, .table-result tr td { border: 1px solid #efefef; padding: 2px 10px 2px 5px; }
.table-result { border-collapse: collapse; min-width: 100%;}
</style>